package com.ys.web.mobao.controller;

import com.alibaba.fastjson.JSON;
import com.ys.base.EnumType;
import com.ys.utils.base.http.ResponseHandler;
import com.ys.utils.base.j2se.JsonUtil;
import com.ys.utils.base.j2se.Logger;
import com.ys.utils.base.j2se.MapHandler;
import com.ys.utils.base.j2se.StringHandler;
import com.ys.utils.http.RSAUtils;
import com.ys.utils.mobao.MobaoPay;
import com.ys.utils.redis.Redis;
import com.ys.utils.spring.config.SystemError;
import com.ys.utils.spring.properties.Config;
import com.ys.web.mobao.manager.BankManager;
import com.ys.web.mobao.model.po.BindCard;
import com.ys.web.mobao.model.po.Notify;
import com.ys.web.mobao.service.MobaoBindCardService;
import com.ys.web.mobao.service.MobaoWithholdingService;
import com.ys.web.mobao.vo.SystemBankVo;
import com.ys.web.pay.manager.PayManager;
import com.ys.web.pay.model.vo.UserBank;
import com.ys.web.pay.service.RedPacketService;
import com.ys.web.pay.service.TransferService;
import com.ys.web.user.info.UserInfoService;
import com.ys.web.user.login.LoginInfo;
import com.ys.web.user.login.LoginService;
import com.ys.web.yinsheng.model.RequestData;
import com.ys.web.yinsheng.model.UserMerchant;
import com.ys.web.yinsheng.service.YinShengService;
import com.ys.web.yinsheng.util.ServiceEnum;
import com.ys.web.yinsheng.util.YinShengClient;
import com.ys.web.yinsheng.util.YsFastPay;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
@RestController
@RequestMapping("/onlinePay/cashier/bindcard/")
public class MobaoBindCardController {
    @Autowired
    private MobaoBindCardService mobaoBindCardService;
    @Autowired
    private LoginService loginService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private YinShengService yinShengService;
    @Autowired
    private RedPacketService redPacketService;
    @Autowired
    private TransferService transferService;
    @Autowired
    private MobaoWithholdingService mobaoWithholdingService;
    /**
     * 支持的银行列表
     *
     * @return
     */
    @RequestMapping("bankList")
    public String bankList() {
        List<SystemBankVo> list = BankManager.list("mb");
        return ResponseHandler.list(list);
    }

    /**
     * 根据银行卡卡号获取银行信息
     *
     * @return
     */
    @RequestMapping("bindCardBin")
    public String bindCardBin(BindCard bindCard) {
        if (Boolean.parseBoolean(Config.pp.get("trading.disable"))) {
            SystemError.wrapBs("500", "系统维护,交易系统已关闭");
        }
        if("ys".equals(StringHandler.getString(Config.pp.get("ys.user.pay.channel"),"ys"))){
            return ResponseHandler.success();
        }
        bindCard.setCardNo(bindCard.getCardNo().replaceAll(" ", ""));
        Map<String,Object> data = null;
        try{
            data = MobaoPay.bindCardBin(bindCard);
        }catch (Exception e){
            Logger.error("获取银行卡bin异常",e);
            SystemError.wrapBs("500","銀行卡号获取银行名称失败，请检查卡号");
        }

        return ResponseHandler.success(data);
    }

    /**
     * @作者: dhf
     * @名称:摩宝绑卡
     * @param uid
     * @param bindCard
     * @时间: 2022/9/7 19:10
     * @备注:
     * @返回值: java.lang.String
     */
    @RequestMapping("submit/mb")
    public String rechargeCreateMb(@RequestAttribute String uid,
                                   BindCard bindCard, @RequestParam(defaultValue = "") String bankCode) {
        if (Boolean.parseBoolean(Config.pp.get("trading.disable"))) {
            SystemError.wrapBs("500", "交易系统已关闭");
        }
        int count = mobaoBindCardService.getUserBankCheckCardNo(bindCard.getCardNo());
        if (count > 0) {
            SystemError.wrapBs("400", "该卡已绑定");
        }
        if(StringHandler.isEmpty(bankCode)){
            Map<String,Object> data = null;
            try{
                data = MobaoPay.bindCardBin(bindCard);
                bindCard.bankCode = StringHandler.getString(data.get("bankCode"));
                bindCard.bankName = StringHandler.getString(data.get("bankName")).split(" ")[0];
            }catch (Exception e){
                Logger.error("获取银行卡bin异常",e);
            }
        }else{
            bindCard.bankCode = bankCode;
            bindCard.setBankName(bindCard.bankName.split(" ")[0]);
        }
        bindCard.setUserId(uid);
        bindCard.setCardNo(bindCard.getCardNo().replaceAll(" ", ""));
        LoginInfo loginInfo = loginService.infoById(uid);
        Map<String, Object> idCard = userInfoService.getUserIdCord(loginInfo.getId());
        if(StringHandler.isNotEmpty(idCard)){
            bindCard.setUserName(StringHandler.getString(idCard.get("realName")));
            bindCard.setIdCardNum(StringHandler.getString(idCard.get("realIdCard")));
        }else{
            SystemError.wrapBs("500", "请实名认证后绑定银行卡");
        }
//        String responseMsg = MobaoPay.bindCard(bindCard);
//        JSONObject jsonObject = JSON.parseObject(responseMsg);
//        if (!jsonObject.getString("retMsg").equals("success") && !jsonObject.getString("retMsg").equals("成功")) {
//            SystemError.wrapBs("400", jsonObject.getString("retMsg"));
//        }
//        JSONObject jsonObject1 = JSON.parseObject(jsonObject.getString("retData"));
//        //signData的值经过BASE64加密，将signData进行BASE64解密得到html，打开html页面进行签约
//        if (jsonObject1.getIntValue("signStatus") == 0) {
//            String signData = jsonObject1.getString("signData");
//            return ResponseHandler.success(MapHandler.initMap("cardToken", "", "signData", signData));
//        } else {
//            bindCard.setCardToken(jsonObject1.getString("signNo"));
//            mobaoBindCardService.saveUserBankMb(bindCard);
//        }
        bindCard.setCardToken(bindCard.getRequestId());
        mobaoBindCardService.saveUserBankMb(bindCard);

        return ResponseHandler.success(MapHandler.initMap("cardToken", bindCard.getCardToken(), "signData", ""));
    }
    /**
     * 银行卡绑定提交
     *
     * @param uid
     * @param bindCard
     * @return
     */
    @RequestMapping("submit")
    public String rechargeCreate(@RequestAttribute String uid, BindCard bindCard) {

        if (Boolean.parseBoolean(Config.pp.get("trading.disable"))) {
            SystemError.wrapBs("500", "交易系统已关闭");
        }
        int count = mobaoBindCardService.getUserBankByCardNo(bindCard.getCardNo());
        if (count > 0) {
            SystemError.wrapBs("400", "该卡已绑定");
        }
        /**支付渠道  mb 摩宝 ys 银盛  sxy 首信易 um U盟 */
        if("ys".equals(StringHandler.getString(Config.pp.get("ys.user.pay.channel"),"ys"))){
            return this.ysBindCard(uid,bindCard);
        }
        return ResponseHandler.success(MapHandler.initMap("cardToken", bindCard.getCardToken(), "signData", ""));
    }


    /**
     * @作者: dhf
     * @名称:银盛绑卡
     * @param uid
     * @param bindCard
     * @时间: 2022/7/18 13:21
     * @备注:
     * @返回值: java.lang.String
     */
    public String ysBindCard(String uid, BindCard bindCard){
        UserMerchant userMerchant = yinShengService.userMerchant(uid);
        if(StringHandler.isEmpty(userMerchant)){
            SystemError.wrapBs("500","该用户实名认证信息有误");
        }

        bindCard.setBankType(YsFastPay.getBankType(bindCard.getBankName()));
        bindCard.setUserId(uid);
        bindCard.setCardToken(bindCard.getRequestId());
        // 组装业务参数
        Map<String,Object> requestMap = new HashMap<>();
        requestMap.put("requestNo",bindCard.getRequestId());
        requestMap.put("merchantNo",userMerchant.merchantNo);//银盛商户号
        requestMap.put("bindFunction","01");//绑卡功能
        requestMap.put("bankAccountNo",bindCard.getCardNo());//银行卡号
        requestMap.put("bankMobile",bindCard.getMobile());//银行预留手机号
        requestMap.put("validTime",bindCard.getValidTime());//银行卡有效期，格式：MMYY，贷记卡必填
        requestMap.put("cvv",bindCard.getCvv());//银行卡安全码，贷记卡必填
        RequestData requestData = new RequestData(requestMap);
        YinShengClient yinShengClient = new YinShengClient(ServiceEnum.WALLET_BIND_CARD);
        Map<String, Object> map = yinShengClient.requestApi(requestData,"绑卡");
        if(StringHandler.isEmpty(map)){
            SystemError.wrapBs("500","绑卡失败");
        }
        Redis.str.set(bindCard.getRequestId(), JsonUtil.toJson(bindCard),12*60*60);
        String authSn = StringHandler.getString(map.get("authSn"));
        Map<String,Object> res = new HashMap<>();
        res.put("authSn",authSn);
        res.put("requestNo",bindCard.getRequestId());
        return ResponseHandler.success(res);
    }
    /**
     * 绑卡查询
     *
     * @return
     */
    @RequestMapping("query")
    public String query(@RequestAttribute long uid) {
        List<UserBank> list = mobaoBindCardService.getUserBankByUserId(uid);
        list = list.stream().peek(x -> {
            x.setCardNo(x.getCardNo().substring(x.getCardNo().length()-4));
            x.setMobile(null);
            x.setIdCardNum(null);
            x.setUserId(null);
        }).collect(Collectors.toList());
        return ResponseHandler.list(list);
    }

    /**
     * 接收绑卡状态的回调
     *
     * @return
     */
    @RequestMapping("send")
    public String send(@RequestBody Notify notify) {
//        System.err.println("接收绑卡状态的回调"+JSON.toJSONString(notify));
        UserBank userBank = mobaoBindCardService.getUserBankByToken(notify.getMerchTradeNo());
        try{
            if(notify.getSignStatus().equals("0")){
                mobaoBindCardService.delUserBankByCardToken(userBank.getUserId(),notify.getMerchTradeNo());
            }
        }catch (Exception e){
            Logger.error("绑卡回调操作失败",e);
        }

        return JSON.toJSONString(MapHandler.initMap("returnCode","1","returnMsg","SUCCESS"));
    }

    /**
     * 卡片解绑
     * @param bindCard
     * @return
     */
    @RequestMapping("unbind")
    public String unbind(@RequestAttribute String uid,BindCard bindCard) {
        if (Boolean.parseBoolean(Config.pp.get("trading.disable"))) {
            SystemError.wrapBs("500", "交易系统已关闭");
        }
        LoginInfo loginInfo = loginService.infoByUid(uid);
        if (!PayManager.validatePayPassword(RSAUtils.decryptField(bindCard.getPayPassword()), loginInfo)) {
            SystemError.wrapBs(EnumType.ResponseCode.ILLEGAL.getCode(), "支付密码错误");
        }
        /**支付渠道  mb 摩宝 ys 银盛  sxy 首信易 um U盟 */
        if("ys".equals(StringHandler.getString(Config.pp.get("ys.user.pay.channel"),"ys"))){
            UserMerchant userMerchant = yinShengService.userMerchant(uid);
            if(StringHandler.isEmpty(userMerchant)){
                SystemError.wrapBs("500","该用户实名认证信息有误");
            }
            //用户是否有未完成的红包
            int redNum = redPacketService.redNum(StringHandler.getLong(uid));
            if(redNum>0){
                SystemError.wrapBs("500","该用户还有未完成的红包,暂时不能解绑");
            }
            //用户是否有未完成的转账
            int transNum = transferService.transNum(StringHandler.getLong(uid));
            if(transNum>0){
                SystemError.wrapBs("500","该用户还有未完成的转账,暂时不能解绑");
            }
            //用户是否有未完成的提现
            int withdrawNum = mobaoWithholdingService.getWithdrawNum(StringHandler.getLong(uid));
            if(withdrawNum>0){
                SystemError.wrapBs("500","该用户还有未完成的提现,暂时不能解绑");
            }
            UserBank userBank = mobaoBindCardService.getUserBank(uid,bindCard.getCardToken());
            if(StringHandler.isEmpty(userBank)){
                SystemError.wrapBs("500","绑卡信息为空");
            }
            // 组装业务参数
            Map<String,Object> requestMap = new HashMap<>();
            requestMap.put("requestNo",bindCard.getRequestId());
            requestMap.put("merchantNo",userMerchant.merchantNo);//银盛商户号
            requestMap.put("linkId",userBank.linkId);//绑卡功能
            RequestData requestData = new RequestData(requestMap);
            YinShengClient yinShengClient = new YinShengClient(ServiceEnum.WALLET_UNBIND);
            Map<String, Object> map = yinShengClient.requestApi(requestData,"银行卡解绑");
            if(StringHandler.isEmpty(map)){
                SystemError.wrapBs("500","解绑失败");
            }
        }
        mobaoBindCardService.delUserBankByCardToken(StringHandler.getLong(uid),bindCard.getCardToken());
        return ResponseHandler.success();
    }
    @RequestMapping("unbind/mb")
    public String unbindMb(@RequestAttribute String uid,BindCard bindCard) {
        if (Boolean.parseBoolean(Config.pp.get("trading.disable"))) {
            SystemError.wrapBs("500", "交易系统已关闭");
        }
        LoginInfo loginInfo = loginService.infoByUid(uid);
        if (!PayManager.validatePayPassword(RSAUtils.decryptField(bindCard.getPayPassword()), loginInfo)) {
            SystemError.wrapBs(EnumType.ResponseCode.ILLEGAL.getCode(), "支付密码错误");
        }
        mobaoBindCardService.delUserBankByCardTokenMb(StringHandler.getLong(uid),bindCard.getCardToken());
        return ResponseHandler.success();
    }
}
